import { get } from 'lodash-es'
import { onBeforeUnmount, onMounted } from 'vue'

export const useHorizontalScroll = (opts = {}) => {
    const { targetRef, elPath = ['value'], auto = true, scrollSize = 100 } = opts

    const getElement = () => {
        return get(targetRef, elPath)
    }

    const addListener = el => {
        if (!el) return
        el.addEventListener('mousewheel', handler, false)
    }

    const removeListener = el => {
        if (!el) return
        el.removeEventListener('mousewheel', handler, false)
    }

    onMounted(() => {
        if (!auto) return
        addListener(getElement())
    })

    onBeforeUnmount(() => {
        if (!auto) return
        removeListener(getElement())
    })

    function handler (event) {
        event.preventDefault()
        // 获取滚动方向
        const detail = event.wheelDelta || event.detail
        // 定义滚动方向
        const moveForwardStep = 1
        const moveBackStep = -1
        // 定义滚动距离
        let step = 0
        // 判断滚动方向
        if (detail < 0) {
            step = moveForwardStep * scrollSize
        } else {
            step = moveBackStep * scrollSize
        }
        // 滚动
        this.scrollLeft += step
    }

    return {
        addListener,
        removeListener
    }
}